import React, { useState } from "react";

const TodoApp = () => {
  // State for todos and loading
  const [todos, setTodos] = useState([]);
  const [loading, setLoading] = useState(false);

  // Mock network requests
  const fetchTodos = async () => {
    setLoading(true);
    try {
      const response = await fetch("https://jsonplaceholder.typicode.com/todos?_limit=5");
      const data = await response.json();
      setTodos(data);
    } catch (error) {
      console.error("Error fetching todos:", error);
    } finally {
      setLoading(false);
    }
  };

  const addSampleTodo = () => {
    const newTodo = {
      id: todos.length + 1,
      title: `Sample Task ${todos.length + 1}`,
      completed: false,
    };
    setTodos([...todos, newTodo]);
  };

  const clearTodos = () => {
    setTodos([]);
  };

  return (
    <div style={{ padding: "20px", fontFamily: "Arial" }}>
      <h1>Todo App</h1>
      <div style={{ marginBottom: "20px" }}>
        <button onClick={fetchTodos} disabled={loading} style={{ marginRight: "10px" }}>
          {loading ? "Loading..." : "Fetch Todos"}
        </button>
        <button onClick={addSampleTodo} style={{ marginRight: "10px" }}>
          Add Sample Todo
        </button>
        <button onClick={clearTodos}>
          Clear Todos
        </button>
      </div>
      <ul>
        {todos.map((todo) => (
          <li key={todo.id} style={{ marginBottom: "5px" }}>
            <span>{todo.title}</span>
            <span style={{ marginLeft: "10px", color: todo.completed ? "green" : "red" }}>
              {todo.completed ? "Completed" : "Pending"}
            </span>
          </li>
        ))}
      </ul>
      {todos.length === 0 && <p>No todos yet!</p>}
    </div>
  );
};

export default TodoApp;